package xhhx.logic;

import com.google.protobuf.MessageLite;
import io.netty.util.internal.TypeParameterMatcher;
import xhhx.cache.PlayerCache;

public abstract class Processor<R, S> {

    private final TypeParameterMatcher matcher;

    public Processor() {
        matcher = TypeParameterMatcher.find(this, Processor.class, "R");
    }

    private boolean acceptInboundMessage(Object msg) {
        return matcher.match(msg);
    }

    public MessageLite Receive(MessageLite msg, PlayerCache playerCache) {
        try {
            if (acceptInboundMessage(msg)) {
                R cast = (R) msg;
                try {
                    S rt = deal(cast, playerCache);
                    return (MessageLite) rt;
                } catch (Exception e) {
                    throw e;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected abstract S deal(R c2s, PlayerCache playerCache);
}
